package com.yl.framework.beans;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @Author 小羊
 * @Date 2/11/2024下午 3:09
 * @ClassName MutablePropertyValues
 * @Description 用来存储和管理多个PropertyValue对象
 */
public class MutablePropertyValues implements Iterable<PropertyValue>{
    private final List<PropertyValue> propertyValueList;
    public MutablePropertyValues() {
        this.propertyValueList = new ArrayList<>();
    }
    public MutablePropertyValues(List<PropertyValue> propertyValueList) {
        if(propertyValueList==null){
            this.propertyValueList = new ArrayList<>();
        }else {
            this.propertyValueList=propertyValueList;
        }

    }

    /**
     * 获取所有的PropertyValue对象，返回以数组的形式
     * @return
     */
    public PropertyValue[] getPropertyValues(){
        //将集合转换为数组返回
        return propertyValueList.toArray(new PropertyValue[0]);
    }

    /**
     * 根据name属性值获取PropertyValue对象
     * @param propertyName
     * @return
     */
    public PropertyValue getPropertyValue(String propertyName){
        for (PropertyValue value : propertyValueList) {
            if(value.getName().equals(propertyName)){
                return value;
            }
        }
        return null;
    }

    /**
     * 判断集合是否为空
     * @return
     */
    public boolean isEmpty(){
        return propertyValueList.isEmpty();
    }
    public MutablePropertyValues addPropertyValue(PropertyValue value){
        //判断集合中存储的PropertyValue对象是否和传递进行的重复了，如果重复了，进行覆盖
        for(int i=0;i< propertyValueList.size();i++){
            if(propertyValueList.get(i).getName().equals(value.getName())){
                propertyValueList.set(i,value);
                return this;
            }
        }
        propertyValueList.add(value);
        return this;
    }

    /**
     * 判断集合中是否有指定name名称的对象
     * @param propertyName
     * @return
     */
    public boolean contains(String propertyName){
        return getPropertyValue(propertyName)!=null;
    }

    /**
     * 获取迭代器对象
     * @return
     */
    @Override
    public Iterator<PropertyValue> iterator() {
        return propertyValueList.iterator();
    }
}
